﻿using KingExGEM;
using NetTaste;
using System;
using System.Collections.Concurrent;
using System.Windows.Documents;
using Def = CommonLibrary.WFFile.SysDef;
namespace DemountCIM.Framework.SECSGEM
{
    //enum VID
    //{
    //    Clock = 1,
    //    PortID = 5505,
    //    PortType = 5500,
    //    PlateID = 5508,
    //    GlueBarCode1 = 5512,
    //    // 涂一个晶托的使用量
    //    GlueDosage1 = 5513,
    //    // 晶托胶余量
    //    GlueAllowance1 = 5514,
    //    // 晶托胶温度
    //    GlueTemperature1 = 5515,
    //    BeamBarCode = 5517,
    //    GlueBarCode2 = 5521,
    //    // 涂一个晶棒的使用量
    //    GlueDosage2 = 5522,
    //    // 晶棒胶余量
    //    GlueAllowance2 = 5523,
    //    // 晶棒胶温度
    //    GlueTemperature2 = 5524,
    //    BrickBarCode = 5525,

    //}
    //enum CEID
    //{
    //    PlateArriveGluingStation1 = 2001,
    //    PlateReadRFID1 = 2002,
    //    GlueReadBarcode1 = 2020,
    //    GluingStart1 = 2003,
    //    GluingFinish1 = 2004,
    //    PlateArriveMountingStation = 2005,
    //    BeamReadBarcode = 2021,
    //    BeamMountingComplete = 2006,
    //    BlockMountingComplete1 = 2007,
    //    EnterHardening = 2008,
    //    ExitHardening = 2009,
    //    PlateArriveGluingStation2 = 2010,
    //    PlateReadRFID2 = 2011,
    //    GlueReadBarcode2 = 2022,
    //    GluingStart2 = 2012,
    //    GluingFinish2 = 2013,
    //    PlateArriveBrickMountingStation = 2014,
    //    BrickReadBarcode = 2023,
    //    BrickMountingComplete = 2015,
    //    BlockMountingComplete2 = 2016,
    //    PlateLeaveBrickMountingStation = 2017,
    //}

    //enum RCMD
    //{
    //    // rfid 校验
    //    VALIDATE_MATERIAL,

    //}


    //  XGem state
    enum _eXGemState
    {
        ExGemState_Unknown = -1,
        ExGemState_Initialized = 0,
        ExGemState_Started,
        ExGemState_Stopped,
        ExGemState_Closed
    };

    //	Communication state
    internal enum _eCommState
    {
        Comm_None = 0,
        Comm_Disabled = 1,
        Comm_WaitCRFromHost,
        Comm_WaitDelay,
        Comm_WaitCRA,
        Comm_Communicating
    };

    //	Control state
    enum _eControlState
    {
        Control_None = 0,
        Control_EqOffline = 1,
        Control_AttemptOnline,
        Control_HostOffline,
        Control_Local,
        Control_Remote
    };

    //	Processing state
    enum _eProcessingState
    {
        Processing_None = 0,
        Processing_Init = 1,
        Processing_Idle,
        Processing_SetUp,
        Processing_Ready,
        Processing_Execuing,
        Processing_Paused
    };

    //	Processing Command
    enum _eProcessingCommand
    {
        ProcCommand_Init = 0,
        ProcCommand_InitIdle = 1,
        ProcCommand_SetUp,
        ProcCommand_Ready,
        ProcCommand_Start,
        ProcCommand_Complete,
        ProcCommand_Stop,
        ProcCommand_Abort,
        ProcCommand_Alarm,
        ProcCommand_Pause,
        ProcCommand_Resume
    };

    public class KingEQP
    {
        #region 添加委托
        private void AddDelegate()
        {
            this.m_kExGem.onGEMEvent += new OnGEMEvent(OnGEMEventHandle);
            this.m_kExGem.onGEMStateEvent += new OnGEMStateEvent(OnGEMStateEventHandle);
            this.m_kExGem.onGEMAlarmEnableStateChanged += new OnGEMAlarmEnableStateChanged(OnGEMAlarmEnableStateChangedHandle);
            this.m_kExGem.onGEMRspAllAlarmInfo += new OnGEMRspAllAlarmInfo(OnGEMRspAllAlarmInfoHandle);
            this.m_kExGem.onGEMRspAllEventInfo += new OnGEMRspAllEventInfo(OnGEMRspAllEventInfoHandle);
            this.m_kExGem.onGEMRspAllReportInfo += new OnGEMRspAllReportInfo(OnGEMRspAllReportInfoHandle);
            this.m_kExGem.onGEMRspAllSVInfo += new OnGEMRspAllSVInfo(OnGEMRspAllSVInfoHandle);
            this.m_kExGem.onGEMRspAllDVInfo += new OnGEMRspAllDVInfo(OnGEMRspAllDVInfoHandle);
            this.m_kExGem.onGEMRspAllEcvInfo += new OnGEMRspAllEcvInfo(OnGEMRspAllEcvInfoHandle);
            this.m_kExGem.onGEMRspAllEnabledAlarm += new OnGEMRspAllEnabledAlarm(OnGEMRspAllEnabledAlarmHandle);
            this.m_kExGem.onGEMRspAllEnabledEvent += new OnGEMRspAllEnabledEvent(OnGEMRspAllEnabledEventHandle);
            this.m_kExGem.onGEMCommStateChanged += new OnGEMCommStateChanged(OnGEMCommStateChangedHandle);
            this.m_kExGem.onGEMControlStateChanged += new OnGEMControlStateChanged(OnGEMControlStateChangedHandle);
            this.m_kExGem.onGEMECVChanged += new OnGEMECVChanged(OnGEMECVChangedHandle);
            this.m_kExGem.onGEMErrorEvent += new OnGEMErrorEvent(OnGEMErrorEventHandle);
            this.m_kExGem.onGEMErrorMessage += new OnGEMErrorMessage(OnGEMErrorMessageHandle);
            this.m_kExGem.onGEMEventEnableStateChanged += new OnGEMEventEnableStateChanged(OnGEMEventEnableStateChangedHandle);
            this.m_kExGem.onGEMEventSend += new OnGEMEventSend(OnGEMEventSendHandle);
            this.m_kExGem.onGEMMessage += new OnGEMMessage(OnGEMMessageHandle);
            this.m_kExGem.onGEMProcessingStateChanged += new OnGEMProcessingStateChanged(OnGEMProcessingStateChangedHandle);
            this.m_kExGem.onGEMRemoteEvent += new OnGEMRemoteEvent(OnGEMRemoteEventHandle);
            this.m_kExGem.onGEMReqChangeECV += new OnGEMReqChangeECV(OnGEMReqChangeECVHandle);
            this.m_kExGem.onGEMReqDateTime += new OnGEMReqDateTime(OnGEMReqDateTimeHandle);
            this.m_kExGem.onGEMReqDateTimeSend += new OnGEMReqDateTimeSend(OnGEMReqDateTimeSendHandle);
            this.m_kExGem.onGEMReqEnhancedRemoteCommand += new OnGEMReqEnhancedRemoteCommand(OnGEMReqEnhancedRemoteCommandHandle);
            this.m_kExGem.onGEMReqOffline += new OnGEMReqOffline(OnGEMReqOfflineHandle);
            this.m_kExGem.onGEMReqOnline += new OnGEMReqOnline(OnGEMReqOnlineHandle);
            this.m_kExGem.onGEMReqPPDelete += new OnGEMReqPPDelete(OnGEMReqPPDeleteHandle);
            this.m_kExGem.onGEMReqPPEx += new OnGEMReqPPEx(OnGEMReqPPExHandle);
            this.m_kExGem.onGEMReqPPFmt += new OnGEMReqPPFmt(OnGEMReqPPFmtHandle);
            this.m_kExGem.onGEMReqPPFmtSend += new OnGEMReqPPFmtSend(OnGEMReqPPFmtSendHandle);
            this.m_kExGem.onGEMReqPPList += new OnGEMReqPPList(OnGEMReqPPListHandle);
            this.m_kExGem.onGEMReqPPLoadInquire += new OnGEMReqPPLoadInquire(OnGEMReqPPLoadInquireHandle);
            this.m_kExGem.onGEMReqPP += new OnGEMReqPP(OnGEMReqPPHandle);
            this.m_kExGem.onGEMReqPPSend += new OnGEMReqPPSend(OnGEMReqPPSendHandle);
            this.m_kExGem.onGEMReqPPSendEx += new OnGEMReqPPSendEx(OnGEMReqPPSendExHandle);
            this.m_kExGem.onGEMReqRemoteCommand += new OnGEMReqRemoteCommand(OnGEMReqRemoteCommandHandle);
            this.m_kExGem.onGEMReqSimpleRemoteCommand += new OnGEMReqSimpleRemoteCommand(OnGEMReqSimpleRemoteCommandHandle);
            this.m_kExGem.onGEMRspDateTime += new OnGEMRspDateTime(OnGEMRspDateTimeHandle);
            this.m_kExGem.onGEMRspLoopback += new OnGEMRspLoopback(OnGEMRspLoopbackHandle);
            this.m_kExGem.onGEMRspPPEx += new OnGEMRspPPEx(OnGEMRspPPExHandle);
            this.m_kExGem.onGEMRspPPFmt += new OnGEMRspPPFmt(OnGEMRspPPFmtHandle);
            this.m_kExGem.onGEMRspPPFmtSend += new OnGEMRspPPFmtSend(OnGEMRspPPFmtSendHandle);
            this.m_kExGem.onGEMRspPPLoadInquire += new OnGEMRspPPLoadInquire(OnGEMRspPPLoadInquireHandle);
            this.m_kExGem.onGEMRspPP += new OnGEMRspPP(OnGEMRspPPHandle);
            this.m_kExGem.onGEMRspPPSendEx += new OnGEMRspPPSendEx(OnGEMRspPPSendExHandle);
            this.m_kExGem.onGEMRspPPSend += new OnGEMRspPPSend(OnGEMRspPPSendHandle);
            this.m_kExGem.onGEMSecondaryMsgReceived += new OnGEMSecondaryMsgReceived(OnGEMSecondaryMsgReceivedHandle);
            this.m_kExGem.onGEMTerminalMessage += new OnGEMTerminalMessage(OnGEMTerminalMessageHandle);
            this.m_kExGem.onGEMTerminalMultiMessage += new OnGEMTerminalMultiMessage(OnGEMTerminalMultiMessageHandle);
            this.m_kExGem.onGEMRspPPVerificationInquire += new OnGEMRspPPVerificationInquire(OnGEMRspPPVerificationInquireHandle);
            this.m_kExGem.onGEMRspPPVerification += new OnGEMRspPPVerification(OnGEMRspPPVerificationHandle);
        }
        #endregion

        #region GEM 事件
        private void OnGEMEventHandle(Int16 nEventId, Int32 lParam)
        {
            string sLog = String.Format("[KingExGEM ==> EQ] OnGEMEvent : nEventId({0}) lParam({1})", nEventId, lParam);
            AddMessage(sLog);
        }
        private void OnGEMStateEventHandle(Int32 state)
        {
            string strState = "";
            switch ((_eXGemState)state)
            {
                case _eXGemState.ExGemState_Initialized:
                    strState = "ExGemState_Initialized";
                    break;
                case _eXGemState.ExGemState_Started:
                    strState = "ExGemState_Started";
                    m_kExGem.GEMSetConnectionEnable(true);             //必须要设置允许连接， 设备才可以被 HOST 连接，否则设备与主机无法连接
                    break;
                case _eXGemState.ExGemState_Stopped:
                    strState = "ExGemState_Stopped";
                    break;
                case _eXGemState.ExGemState_Closed:
                    strState = "ExGemState_Closed";
                    break;
                default:
                    strState = "ExGemState_Unknown";
                    break;
            }
            string sLog = String.Format("[KingExGEM ==> EQ] OnGEMStateEvent : state({0})", strState);
            AddMessage(sLog);
        }
        private void OnGEMErrorMessageHandle(Int32 nMsgId, byte bFunction, byte[] pHeader)
        {
            string sLog = String.Format("[KingExGEM ==> EQ] OnGEMErrorMessage : nMsgId({0}) bFunction({1})", nMsgId, bFunction);
            AddMessage(sLog);
        }
        private void OnGEMErrorEventHandle(string sInterfaceName, string sErrorInfo)
        {
            string sLog = String.Format("[KingExGEM ==> EQ] OnGEMErrorEvent : ErrorName({0}) ErrorCode({1})", sInterfaceName, sErrorInfo);
            AddMessage(sLog);
        }
        /// <summary>
        /// 未使用
        /// </summary>
        /// <param name="sMsg"></param>
        private void OnGEMLogMessageHandle(string sMsg)
        {
            AddMessage("[KingExGEM ==> EQ] OnGEMLogMessage :");
            string[] sMessage = sMsg.Split('\n');
            for (int i = 0; i < sMessage.Count(); i++)
            {
                if (sMessage[i].Length > 0)
                    AddMessage2(sMessage[i]);
            }
        }
        private void OnGEMRspAllSVInfoHandle(Int32[] pnSvid, string[] psName, string[] psFormat, UInt32[] pnlen, string[] psMins, string[] psMaxs, string[] psUnits)
        {
            UInt32 nCount = (uint)pnSvid.Length;

            string sLog = String.Format("[KingExGEM ==> EQ] OnGEMRspAllSVInfo : nCount({0})", nCount);
            AddMessage(sLog);

            for (UInt32 i = 0; i < nCount; i++)
            {
                sLog = String.Format("    nVid({0}) sName({1}) sFormat({2}) nlen({3}) sMin({4}) sMax({5}) sUnit({6})",
                    pnSvid[i], psName[i], psFormat[i], pnlen[i], psMins[i], psMaxs[i], psUnits[i]);
                AddMessage(sLog);
            }
        }
        private void OnGEMRspAllDVInfoHandle(Int32[] pnDvid, string[] psName, string[] psFormat, UInt32[] pnlen, string[] psMins, string[] psMaxs, string[] psUnits)
        {
            UInt32 nCount = (uint)pnDvid.Length;

            string sLog = String.Format("[KingExGEM ==> EQ] OnGEMRspAllDVInfo : nCount({0})", nCount);
            AddMessage(sLog);

            for (UInt32 i = 0; i < nCount; i++)
            {
                sLog = String.Format("    nVid({0}) sName({1}) sFormat({2}) nlen({3}) sMin({4}) sMax({5}) sUnit({6})",
                    pnDvid[i], psName[i], psFormat[i], pnlen[i], psMins[i], psMaxs[i], psUnits[i]);
                AddMessage(sLog);
            }
        }
        private void OnGEMRspAllEcvInfoHandle(Int32[] pnEcIds, string[] psNames, string[] psFormat, UInt32[] pnlen, string[] psDefs, string[] psMins, string[] psMaxs, string[] psUnits)
        {
            UInt32 nCount = (uint)pnEcIds.Length;

            string sLog = String.Format("[KingExGEM ==> EQ] OnGEMRspAllEcvInfo : nCount({0})", nCount);
            AddMessage(sLog);

            for (UInt32 i = 0; i < nCount; i++)
            {
                sLog = String.Format("    nVid({0}) sName({1}) sFormat({2}) nlen({3}) sDef({4}) sMin({5}) sMax({6}) sUnit({7})",
                    pnEcIds[i], psNames[i], psFormat[i], pnlen[i], psDefs[i], psMins[i], psMaxs[i], psUnits[i]);
                AddMessage(sLog);
            }
        }
        private void OnGEMRspAllAlarmInfoHandle(Int32[] pnAlid, Int32[] pnAlcd, string[] psAltx, bool[] pnEnable)
        {
            UInt32 nCount = (uint)pnAlid.Length;

            string sLog = String.Format("[KingExGEM ==> EQ] OnGEMRspAllAlarmInfo : nCount({0})", nCount);
            AddMessage(sLog);

            for (UInt32 i = 0; i < nCount; i++)
            {
                sLog = String.Format("    nAlid({0}) nAlcd({1}) sAltx({2}) nEnable({3})",
                    pnAlid[i], pnAlcd[i], psAltx[i], pnEnable[i]);
                AddMessage(sLog);
            }
        }
        private void OnGEMRspAllEventInfoHandle(Int32[] pnCeid, string[] pName, bool[] pEnable, string[] pDescription, Int32[][] pnReportID)
        {
            UInt32 nCount = (uint)pnCeid.Length;

            string sLog = String.Format("[KingExGEM ==> EQ] OnGEMRspAllEventInfo : nCount({0})", nCount);
            AddMessage(sLog);

            for (UInt32 i = 0; i < nCount; i++)
            {
                string sTemp = "";
                for (UInt32 j = 0; j < pnReportID[i].Length; j++)
                {
                    if (j == 0)
                        sTemp += String.Format("{0}", pnReportID[i][j]);
                    else
                        sTemp += String.Format(", {0}", pnReportID[i][j]);
                }
                sLog = String.Format("    nCeid({0}) sName({1}) Enable({2}) Description({3}) nRptidCount({4}) nReportID({5})",
                pnCeid[i], pName[i], pEnable[i], pDescription[i], pnReportID[i].Length, sTemp);
                AddMessage(sLog);
            }
        }
        private void OnGEMRspAllReportInfoHandle(Int32[] pnRptid, string[] pName, Int32[][] pnVid)
        {
            UInt32 nCount = (uint)pnRptid.Length;

            string sLog = String.Format("[KingExGEM ==> EQ] OnGEMRspAllReport : nCount({0})", nCount);
            AddMessage(sLog);

            for (UInt32 i = 0; i < nCount; i++)
            {
                string sTemp = "";
                for (UInt32 j = 0; j < pnVid[i].Length; j++)
                {
                    if (j == 0)
                        sTemp += String.Format("{0}", pnVid[i][j]);
                    else
                        sTemp += String.Format(", {0}", pnVid[i][j]);
                }
                sLog = String.Format("    pnRptid({0}) sName({1}) vidCount({2}) nVid({3})",
                pnRptid[i], pName[i], pnVid[i].Length, sTemp);
                AddMessage(sLog);
            }
        }
        private void OnGEMRspAllEnabledAlarmHandle(Int32[] pnAlid)
        {
            UInt32 nCount = (uint)pnAlid.Length;

            string alidstr = "ALID =";
            for (int i = 0; i < nCount; i++)
            {
                if (i == 0)
                    alidstr = alidstr + string.Format("{0}", pnAlid[i]);
                else
                    alidstr = alidstr + "," + string.Format("{0}", pnAlid[i]);
            }
            string sLog = String.Format("[KingExGEM ==> EQ] OnGEMRspAllEnabledAlarm : nAlid({0})", alidstr);
            AddMessage(sLog);
        }
        private void OnGEMRspAllEnabledEventHandle(Int32[] pnCeid)
        {
            UInt32 nCount = (uint)pnCeid.Length;

            string ceidstr = "CEID =";
            for (int i = 0; i < nCount; i++)
            {
                if (i == 0)
                    ceidstr = ceidstr + string.Format("{0}", pnCeid[i]);
                else
                    ceidstr = ceidstr + "," + string.Format("{0}", pnCeid[i]);
            }
            string sLog = String.Format("[KingExGEM ==> EQ] OnGEMRspAllEnabledEvent : nCeid({0})", ceidstr);
            AddMessage(sLog);
        }
        private void OnGEMECVChangedHandle(Int32[] plEcIds, string[] psVals)
        {
            UInt32 nCount = (uint)plEcIds.Length;

            string sLog = String.Format("[KingExGEM ==> EQ] OnGEMECVChanged : nCount({0})", nCount);
            AddMessage(sLog);

            for (UInt32 i = 0; i < nCount; i++)
            {
                sLog = String.Format("    EcId({0}) sVal({1})",
                    plEcIds[i], psVals[i]);
                AddMessage(sLog);
            }
        }
        private void OnGEMReqChangeECVHandle(Int32 nMsgId, Int32[] plEcIds, string[] psVals)
        {
            UInt32 nCount = (uint)plEcIds.Length;

            string sLog = String.Format("[KingExGEM ==> EQ] OnGEMReqChangeECV : nMsgId({0}) nCount({1})", nMsgId, nCount);
            AddMessage(sLog);

            for (UInt32 i = 0; i < nCount; i++)
            {
                sLog = String.Format("    EcId({0}) sVal({1})",
                    plEcIds[i], psVals[i]);
                AddMessage(sLog);
            }

            //回复
            AddMessage(String.Format("[EQ ==> KingExGEM] GemRspEcvChange: bState(0) Return({0})", m_kExGem.GEMRspEcvChange(nMsgId, 0)));
        }
        private void OnGEMReqDateTimeSendHandle(Int32 nMsgId, string sSystemTime)
        {
            string sLog = String.Format("[KingExGEM ==> EQ] OnGEMReqDateTimeSend : nMsgId({0}) sSystemTime({1})", nMsgId, sSystemTime);
            AddMessage(sLog);

            //回复    VID改成UNIT4
            //AddMessage(String.Format("[EQ ==> KingExGEM] GemRspDateTimeSend: bState(0) Return({1})", m_kExGem.GEMRspDateTimeSend(nMsgId, 0)));
        }
        private void OnGEMRspDateTimeHandle(string sSystemTime)
        {
            string sLog = String.Format("[KingExGEM ==> EQ] OnGEMRspDateTime : sSystemTime({0})", sSystemTime);
            AddMessage(sLog);
        }

        /// <summary>
        /// 远程命令校验
        /// </summary>
        /// <param name="nMsgId"></param>
        /// <param name="sRcmd"></param>
        private void OnGEMReqSimpleRemoteCommandHandle(Int32 nMsgId, string sRcmd)
        {
            string sLog = String.Format("[KingExGEM ==> EQ] OnGEMReqSimpleRemoteCommand : nMsgId({0}) sRcmd({1})", nMsgId, sRcmd);
            AddMessage(sLog);

            byte bHcAck = 0;
            AddMessage(String.Format("[EQ ==> KingExGEM] GemRspSimpleRemoteCommand: HcAck({0}) Return({1})", bHcAck, m_kExGem.GEMRspSimpleRemoteCommand(nMsgId, bHcAck)));
        }
        private void OnGEMReqRemoteCommandHandle(Int32 nMsgId, string sRcmd, string[] psNames, string[] psVals)
        {
            UInt32 nCount = (uint)psNames.Length;

            string sLog = String.Format("[KingExGEM ==> EQ] OnGEMReqRemoteCommand : nMsgId({0}) sRcmd({1}) nCount({2})", nMsgId, sRcmd, nCount);
            AddMessage(sLog);

            for (UInt32 i = 0; i < nCount; i++)
            {
                sLog = String.Format("    sNames({0}) sVals({1})",
                    psNames[i], psVals[i]);
                AddMessage(sLog);
            }


            //回复
            string[] pName = { "" };
            byte[] pAck = { 0 };
            byte bHcAck = 0;
            AddMessage(String.Format("[EQ ==> KingExGEM] GemRspRemoteCommand: HcAck({0}) Return({1})", bHcAck, m_kExGem.GEMRspRemoteCommand(nMsgId, bHcAck, pName, pAck)));
        }
        private void OnGEMReqEnhancedRemoteCommandHandle(Int32 nMsgId, string sObjspec, string sRcmd, string[] psNames, string[] psVals)
        {
            UInt32 nCount = (uint)psNames.Length;

            string sLog = String.Format("[KingExGEM ==> EQ] OnGEMReqEnhancedRemoteCommand : nMsgId({0}) sObjspec({1}) sRcmd({2}) nCount({3})", nMsgId, sObjspec, sRcmd, nCount);
            AddMessage(sLog);

            for (UInt32 i = 0; i < nCount; i++)
            {
                sLog = String.Format("    sNames({0}) sVals({1})",
                    psNames[i], psVals[i]);
                AddMessage(sLog);
            }

            //回复
            string[] pName = { "" };
            byte[] pAck = { 0 };
            byte bHcAck = 0;
            AddMessage(String.Format("[EQ ==> KingExGEM] GemRspEnhancedRemoteCommand: HcAck({0}) Return({1})", bHcAck, m_kExGem.GEMRspEnhancedRemoteCommand(nMsgId, bHcAck, pName, pAck)));

            switch (sRcmd)
            {
                case "VALIDATE_CARRIER":
                    {
                        var carrierID = psVals[1];

                        if (rfidReadStatus.Any(a => a.Key == carrierID))
                        {
                            rfidReadStatus.TryRemove(carrierID, out bool val);
                        }
                        rfidReadStatus.TryAdd(carrierID, psVals[5] == "OK");
                        break;
                    }
                case "UPDATE_RFID":
                    {
                        var carrierID = psVals[1];

                        if (rfidReadStatus.Any(a => a.Key == carrierID))
                        {
                            rfidReadStatus.TryRemove(carrierID, out bool val);
                        }
                        rfidReadStatus.TryAdd(carrierID, psVals[3] == "OK");

                        break;
                    }
                default:
                    break;
            }


        }
        private void OnGEMSecondaryMsgReceivedHandle(Int32 nS, Int32 nF, Int32 nSysbyte, string sParam1, string sParam2, string sParam3)
        {
            string sLog = String.Format("[KingExGEM ==> EQ] OnGEMSecondaryMsgReceived : Stream({0}) Function({1}) nSysbyte({2}) sParam1({3}) sParam2({4}) sParam3({5})",
                nS, nF, nSysbyte, sParam1, sParam2, sParam3);
            AddMessage(sLog);
        }
        private void OnGEMTerminalMessageHandle(Int32 nMsgId, Int32 nTid, string sMsg)
        {
            string sLog = String.Format("[KingExGEM ==> EQ] OnGEMTerminalMessage : nMsgId({0}) nTid({1}) sMsg({2})", nMsgId, nTid, sMsg);
            AddMessage(sLog);

            //回复0
            AddMessage(String.Format("[EQ ==> KingExGEM] GemRspTerminalMessageSend: bState(0) Return({0})", m_kExGem.GEMRspTerminalMessageSend(nMsgId, 0)));
        }
        private void OnGEMTerminalMultiMessageHandle(Int32 nMsgId, Int32 nTid, string[] psMsg)
        {
            UInt32 nCount = (uint)psMsg.Length;

            string sLog = String.Format("[KingExGEM ==> EQ] OnGEMTerminalMultiMessage : nMsgId({0}) nTid({1}) nCount({2})", nMsgId, nTid, nCount);
            AddMessage(sLog);

            for (UInt32 i = 0; i < nCount; i++)
            {
                sLog = String.Format("    psMsg({0}))", psMsg[i]);
                AddMessage(sLog);
            }

            //回复
            AddMessage(String.Format("[EQ ==> KingExGEM] GemRspMultiTerminalMessageSend: bState(0) Return({0})", m_kExGem.GEMRspMultiTerminalMessageSend(nMsgId, 0)));
        }
        private void OnGEMRspLoopbackHandle(byte[] pbAbs)
        {
            UInt32 nCount = (uint)pbAbs.Length;

            string sTemp = "";
            for (UInt32 i = 0; i < nCount; i++)
            {
                if (i == 0)
                    sTemp += String.Format("{0}", pbAbs[i]);
                else
                    sTemp += String.Format(" {0}", pbAbs[i]);
            }
            string sLog = String.Format("[KingExGEM ==> EQ] OnGEMRspLoopback: nCount({0}) pbAbs({1})", nCount, sTemp);
            AddMessage(sLog);
        }
        private void OnGEMAlarmEnableStateChangedHandle(byte bAled, Int32[] pnAlid)
        {
            string sTemp = "";
            UInt32 nCount = (uint)pnAlid.Length;
            for (UInt32 i = 0; i < nCount; i++)
            {
                if (i == 0)
                    sTemp += String.Format("{0}", pnAlid[i]);
                else
                    sTemp += String.Format(" {0}", pnAlid[i]);
            }
            string sLog = String.Format("[KingExGEM ==> EQ] OnGEMAlarmEnableStateChanged: bAled({0}) nCount({1}) pnAlid({2})", bAled, nCount, sTemp);
            AddMessage(sLog);
        }

        /// <summary>
        /// 事件回复
        /// </summary>
        /// <param name="bCeed"></param>
        /// <param name="pnCeid"></param>
        private void OnGEMEventEnableStateChangedHandle(byte bCeed, Int32[] pnCeid)
        {
            UInt32 nCount = (uint)pnCeid.Length;

            string sTemp = "";
            for (UInt32 i = 0; i < nCount; i++)
            {
                if (i == 0)
                    sTemp += String.Format("{0}", pnCeid[i]);
                else
                    sTemp += String.Format(" {0}", pnCeid[i]);
            }
            string sLog = String.Format("[KingExGEM ==> EQ] OnGEMEventEnableStateChanged: bAled({0}) nCount({1}) pnAlid({2})", bCeed, nCount, sTemp);
            AddMessage(sLog);
        }
        private void OnGEMReqPPLoadInquireHandle(Int32 nMsgId, string sPpid, UInt32 nLength)
        {
            string sLog = String.Format("[KingExGEM ==> EQ] OnGEMReqPPLoadInquire: nMsgId({0}) sPpid({1}) nLength({2})", nMsgId, sPpid, nLength);
            AddMessage(sLog);

            AddMessage(String.Format("[EQ ==> KingExGEM] OnGEMRspPPLoadInquire: ack({0}) Return({1})", 0, m_kExGem.GEMRspPPLoadInquire(nMsgId, 0)));
        }
        private void OnGEMReqPPHandle(Int32 nMsgId, string sPpid)
        {
            string sLog = String.Format("[KingExGEM ==> EQ] OnGEMReqPP: nMsgId({0}) sPpid({1})", nMsgId, sPpid);
            AddMessage(sLog);

            //回复S7F6
            string strPPBody = "parm1=10,param2=30,param3=3.6";
            byte[] byteArray = System.Text.Encoding.Default.GetBytes(strPPBody);

            AddMessage(String.Format("[EQ ==> KingExGEM] GemRspPP: sPpid({0}) Body({1}) Return({2})", sPpid, strPPBody, m_kExGem.GEMRspPP(nMsgId, sPpid, byteArray)));
        }
        private void OnGEMRspPPHandle(string sPpid, byte[] pbBody)
        {
            string sLog = String.Format("[KingExGEM ==> EQ] OnGEMRspPP: sPpid({0}) nLength({1}) pbBody({2})", sPpid, pbBody.Length, pbBody);
            AddMessage(sLog);
        }
        private void OnGEMReqPPExHandle(Int32 nMsgId, string sPpid, string sRecipePath)
        {
            string sLog = String.Format("[KingExGEM ==> EQ] OnGEMReqPPEx: nMsgId({0}) sPpid({1}) sRecipePath({2})", nMsgId, sPpid, sRecipePath);
            AddMessage(sLog);

            AddMessage(String.Format("[EQ ==> KingExGEM] GemRspPPEx: sPpid({0}) Return({1})", sPpid, m_kExGem.GEMRspPPEx(nMsgId, sPpid)));
        }
        private void OnGEMRspPPExHandle(string sPpid, string sRecipePath)
        {
            string sLog = String.Format("[KingExGEM ==> EQ] OnGEMRspPPEx: sPpid({0}) sRecipePath({1})", sPpid, sRecipePath);
            AddMessage(sLog);
        }
        private void OnGEMReqPPSendHandle(Int32 nMsgId, string sPpid, byte[] pbBody)
        {
            string sLog = String.Format("[KingExGEM ==> EQ] OnGEMReqPPSend: nMsgId({0}) sPpid({1}) nLength({2}) pbBody({3})", nMsgId, sPpid, pbBody.Length, pbBody);
            AddMessage(sLog);

            AddMessage(String.Format("[EQ ==> KingExGEM] GemRspPPSend: bState(0) Return({0})", m_kExGem.GEMRspPPSend(nMsgId, 0)));
        }
        private void OnGEMReqPPSendExHandle(Int32 nMsgId, string sPpid, string sRecipePath)
        {
            string sLog = String.Format("[KingExGEM ==> EQ] OnGEMReqPPSendEx: nMsgId({0}) sPpid({1}) sRecipePath({2})", nMsgId, sPpid, sRecipePath);
            AddMessage(sLog);

            AddMessage(String.Format("[EQ ==> KingExGEM] GemRspPPSend: bState(0) Return({0})", m_kExGem.GEMRspPPSend(nMsgId, 0)));
        }
        private void OnGEMRspPPSendExHandle(Int32 nResult)
        {
            string sLog = String.Format("[KingExGEM ==> EQ] OnGEMRspPPSendEx: nResult({0})", nResult);
            AddMessage(sLog);
        }
        private void OnGEMReqPPFmtHandle(Int32 nMsgId, string sPpid)
        {
            string sLog = String.Format("[KingExGEM ==> EQ] OnGEMReqPPFmt: nMsgId({0}) sPpid({1})", nMsgId, sPpid);
            AddMessage(sLog);

            //回复S7F26
            string[] cCode = { "1", "2" };
            uint[] pCount = { 2, 2 };
            string[][] paramName = new string[][] { new string[] { "1.param1", "1.param2" }, new string[] { "2.param1", "2.param2" } };
            int rsp = m_kExGem.GEMRspPPFmt(nMsgId, sPpid, "test", "0.1", cCode, paramName);
            AddMessage(String.Format("[EQ ==> KingExGEM] GemRspPPFmt: sPpid({0}) Return({1})", sPpid, rsp));
        }
        private void OnGEMRspPPFmtHandle(string sPpid, string sMdln, string sSoftRev, string[] psCCode, string[][] psParamNames)
        {
            UInt32 nCount = (uint)psCCode.Length;

            string sLog = String.Format("[KingExGEM ==> EQ] OnGEMRspPPFmt : sPpid({0}) sMdln({1}) sSoftRev({2}) nCount({3})",
                sPpid, sMdln, sSoftRev, nCount);
            AddMessage(sLog);

            for (UInt32 i = 0; i < nCount; i++)
            {
                string sTemp = "";
                for (UInt32 j = 0; j < psParamNames[i].Length; j++)
                {
                    if (j == 0)
                        sTemp += String.Format("{0}", psParamNames[i][j]);
                    else
                        sTemp += String.Format(", {0}", psParamNames[i][j]);
                }
                sLog = String.Format("    psCCode({0}) plParamCount({1}) psParamNames({2})", psCCode[i], psParamNames[i].Length, sTemp);
                AddMessage(sLog);
            }
        }
        private void OnGEMReqPPFmtSendHandle(Int32 nMsgId, string sPpid, string sMdln, string sSoftRev, string[] psCCode, string[][] psParamNames)
        {
            UInt32 nCount = (uint)psCCode.Length;

            string sLog = String.Format("[KingExGEM ==> EQ] OnGEMReqPPFmtSend : nMsgId({0}) sPpid({1}) sMdln({2}) sSoftRev({3}) nCount({4})",
                nMsgId, sPpid, sMdln, sSoftRev, nCount);
            AddMessage(sLog);

            UInt32 nPos = 0;
            for (UInt32 i = 0; i < nCount; i++)
            {
                string sTemp = "";
                for (UInt32 j = 0; j < psParamNames[i].Length; j++)
                {
                    if (j == 0)
                        sTemp += String.Format("{0}", psParamNames[nPos++]);
                    else
                        sTemp += String.Format(", {0}", psParamNames[nPos++]);
                }
                sLog = String.Format("    psCCode({0}) plParamCount({1}) psParamNames({2})", psCCode[i], psParamNames[i].Length, sTemp);
                AddMessage(sLog);
            }

            //回复S7F24
            AddMessage(String.Format("[EQ ==> KingExGEM] GemRspPPFmtSend: bState(0) Return({0})", m_kExGem.GEMRspPPFmtSend(nMsgId, 0)));
        }
        private void OnGEMReqPPDeleteHandle(Int32 nMsgId, string[] psPpid)
        {
            UInt32 nCount = (uint)psPpid.Length;
            string sLog = String.Format("[KingExGEM ==> EQ] OnGEMReqPPDelete: nMsgId({0}) nCount({1})", nMsgId, nCount);
            AddMessage(sLog);

            for (UInt32 i = 0; i < nCount; i++)
            {
                sLog = String.Format("    sPpid({0})", psPpid[i]);
                AddMessage(sLog);
            }

            //回复
            AddMessage(String.Format("[EQ ==> KingExGEM] GemRspPPDelete: bState(0) Return({0})", m_kExGem.GEMRspPPDelete(nMsgId, 0)));
        }
        /// <summary>
        /// 通讯状态改变
        /// </summary>
        /// <param name="nState"></param>
        /// <param name="prelState"></param>
        private void OnGEMCommStateChangedHandle(int nState, int prelState)
        {
            string tempContent = "";
            switch (nState)
            {
                case 0:
                    tempContent = "Unknown State";
                    break;
                case 1:
                    tempContent = "Disabled";
                    break;
                case 2:
                    tempContent = "WaitCRFromHost";
                    break;
                case 3:
                    tempContent = "WaitDelay";
                    break;
                case 4:
                    tempContent = "WaitCRA";
                    break;
                case 5:
                    tempContent = "Communicating";

                    break;
            }
            eCommState = (_eCommState)nState;

            string sLog = String.Format("[KingExGEM ==> EQ] OnGEMCommStateChanged:{0}", tempContent);
            AddMessage(sLog);
        }
        /// <summary>
        ///  控制状态改变
        /// </summary>
        /// <param name="nState"></param>
        /// <param name="prelState"></param>
        private void OnGEMControlStateChangedHandle(int nState, int prelState)
        {
            string tempContent = "";
            switch (nState)
            {
                case 0:
                    tempContent = "Unknown State";
                    break;
                case 1:
                    tempContent = "EqOffline";
                    break;
                case 2:
                    tempContent = "AttemptOnline";
                    break;
                case 3:
                    tempContent = "HostOffline";
                    break;
                case 4:
                    tempContent = "Local";
                    break;
                case 5:
                    tempContent = "Remote";
                    break;
            }
            eControlState = (_eControlState)nState;
            string sLog = String.Format("[KingExGEM ==> EQ] OnGEMControlStateChanged:{0}", tempContent);
            AddMessage(sLog);
        }
        private void OnGEMEventSendHandle(int nCeid, int nSysbyte)
        {
            string sLog = String.Format("[KingExGEM ==> EQ] OnGEMEventSend: nCeid({0}) nSysbyte({1})", nCeid, nSysbyte);
            //AddMessage(sLog);
        }
        private void OnGEMMessageHandle(Semion message)
        {
            short nDevId;
            Int32 nRsp;
            Int32 nSysbyte;
            byte streamID, funcID, bWbit;

            uint nCount, nCount1;
            ushort[] usVal;
            byte[] byteVal;
            string str;

            nRsp = message.GEMLoadSecsMsg(out nDevId, out streamID, out funcID, out nSysbyte, out bWbit);

            string sLog = String.Format("[KingExGEM ==> EQ] OnGEMMessage: nDevId({0}) streamID({1}) funcID({2}) nSysbyte({3}) bWbit({4})",
                nDevId, streamID, funcID, nSysbyte, bWbit);
            AddMessage(sLog);


            //在这里可以实现各种自定义SECS-II消息的接收和回复
            if (streamID == 101 && funcID == 101)                   //收到 S101F101
            {
                //解析S101F101
                //          LIST, 2
                //              UINT1, 1 [ORDERVALUE] <>
                //              LIST, n
                //                  LIST, 2
                //                      UINT2, 1 [VID] <>
                //                      ASCII, n [TEXT] <>
                nRsp = message.GEMGetListItem(out nCount);
                nRsp = message.GEMGetUint1Item(out byteVal);
                nRsp = message.GEMGetListItem(out nCount1);
                for (uint i = 0; i < nCount1; i++)
                {
                    nRsp = message.GEMGetListItem(out nCount);
                    nRsp = message.GEMGetUint2Item(out usVal);
                    nRsp = message.GEMGetAsciiItem(out str);
                }

                //回复S101F102
                //          BINARY, n [ABS] <>
                byte[] pbAck = { 0 };
                Semion rspMessage = new Semion();
                nRsp = rspMessage.GEMSetBinaryItem(pbAck);
                nRsp = m_kExGem.GEMSendSecsMessage(rspMessage, 101, 102, nSysbyte);
            }
        }
        private void OnGEMProcessingStateChangedHandle(int nState, int prelState)
        {
            string tempContent = "";
            switch (nState)
            {
                case 0:
                    tempContent = "Processing_None";
                    break;
                case 1:
                    tempContent = "Processing_Init";
                    break;
                case 2:
                    tempContent = "Processing_Idle";
                    break;
                case 3:
                    tempContent = "Processing_SetUp";
                    break;
                case 4:
                    tempContent = "Processing_Ready";
                    break;
                case 5:
                    tempContent = "Processing_Execuing";
                    break;
                case 6:
                    tempContent = "Processing_Paused";
                    break;
            }

            string sLog = String.Format("[KingExGEM ==> EQ] OnGEMProcessingStateChanged:{0}", tempContent);
            //AddMessage(sLog);
        }
        private void OnGEMRemoteEventHandle(uint nPort, short nEventId, int nParam)
        {
            string sLog = String.Format("[KingExGEM ==> EQ] OnGEMRemoteEvent : nPort({0})  nEventId({1}) lParam({2})", nPort, nEventId, nParam);
            //AddMessage(sLog);
        }
        private void OnGEMReqDateTimeHandle(int nMsgId)
        {
            string sLog = String.Format("[KingExGEM ==> EQ] OnGEMReqDateTime : nMsgId({0})", nMsgId);
            //AddMessage(sLog);

            //回复
            //AddMessage(String.Format("[EQ ==> KingExGEM] GemRspDateTime: Time(2022041313470001) Return({0})",m_kExGem.GEMRspDateTime(nMsgId, "2022041313470001")));
        }
        private void OnGEMReqOfflineHandle(int nMsgId, int nFromState, int nToState)
        {
            string sLog = String.Format("[KingExGEM ==> EQ] OnGEMReqOffline : nMsgId({0})", nMsgId);
            AddMessage(sLog);

            //回复
            AddMessage(String.Format("[EQ ==> KingExGEM] GemRspOffline: bState(0) Return({0})", m_kExGem.GEMRspOffline(nMsgId, 0)));
        }
        private void OnGEMReqOnlineHandle(int nMsgId, int nFromState, int nToState)
        {
            string sLog = String.Format("[KingExGEM ==> EQ] OnGEMReqOnline : nMsgId({0})", nMsgId);
            AddMessage(sLog);

            //回复
            AddMessage(String.Format("[EQ ==> KingExGEM] GemRspOnline: bState(0) Return({0})", m_kExGem.GEMRspOnline(nMsgId, 0)));
        }
        private void OnGEMReqPPListHandle(int nMsgId)
        {
            string sLog = String.Format("[KingExGEM ==> EQ] OnGEMReqPPList : nMsgId({0})", nMsgId);
            //AddMessage(sLog);

            string[] ppid = { "ppid1", "ppid2", "ppid3" };
            //回复
            //AddMessage(String.Format("[EQ ==> KingExGEM] GEMRspPPList:  Return({0})",m_kExGem.GEMRspPPList(nMsgId, ppid)));
        }
        private void OnGEMRspPPFmtSendHandle(int nResult)
        {
            string sLog = String.Format("[KingExGEM ==> EQ] OnGEMRspPPFmtSend : nResult({0})", nResult);
            //AddMessage(sLog);
        }
        private void OnGEMRspPPLoadInquireHandle(int nResult)
        {
            string sLog = String.Format("[KingExGEM ==> EQ] OnGEMRspPPLoadInquire : nResult({0})", nResult);
            //AddMessage(sLog);
        }
        private void OnGEMRspPPSendHandle(int nResult)
        {
            string sLog = String.Format("[KingExGEM ==> EQ] OnGEMRspPPSend : nResult({0})", nResult);
            //AddMessage(sLog);
        }
        private void OnGEMRspPPVerificationInquireHandle(int nResult)
        {
            string sLog = String.Format("[KingExGEM ==> EQ] OnGEMRspPPVerificationInquire : nResult({0})", nResult);
            //AddMessage(sLog);
        }
        private void OnGEMRspPPVerificationHandle()
        {
            //AddMessage("[KingExGEM ==> EQ] OnGEMRspPPVerification");
        }
        #endregion

        private static KingEQP eqp;                                 // 全局对象
        public event AddMessageCallBack AddMessageEvent;
        public event AddMessage2CallBack AddMessage2Event;

        KingExGemCSharp m_kExGem;                                   // secs/gem 对象
        private _eCommState eCommState;                             // 通讯状态
        private _eControlState eControlState;                       // 控制状态


        private ConcurrentDictionary<string, bool> rfidReadStatus;               // 不同位置的RFID读取状态

        public KingEQP()
        {
            m_kExGem = new KingExGemCSharp();

            rfidReadStatus = new ConcurrentDictionary<string, bool>();

            AddDelegate();
        }



        /// <summary>
        /// 获取全局对象
        /// </summary>
        /// <returns></returns>
        public static KingEQP GetInstance()
        {
            if (null == eqp)
            {
                eqp = new KingEQP();
            }
            return eqp;
        }

        #region 1.初始化和启动

        /// <summary>
        /// 初始化 "System\\DemounterConfig\\DemounterConfig.kgprj"
        /// </summary>
        /// <param name="msg"></param>
        public bool KingInitialize(string relPath)
        {
            string path = Def.GetAbsPathName(relPath);
            int rsp = m_kExGem.GEMInitialize(path);

            if (rsp >= 0)
            {
                AddMessage("[EQ ==> KingExGEM] Initialize succeed");
                return true;
            }
            else
            {
                AddMessage("[EQ ==> KingExGEM] Initialize failed. Return {0}", rsp);
                return false;
            }
        }

        /// <summary>
        /// 启动 KingExGEM
        /// </summary>
        public bool KingStart()
        {
            int rsp = m_kExGem.GEMStart();
            if (rsp >= 0)
            {
                AddMessage("[EQ ==> KingExGEM] Start succeed");
                return true;
            }
            else
            {
                AddMessage("[EQ ==> KingExGEM] Start failed. Return {0}", rsp);
                return false;
            }
        }

        /// <summary>
        /// 停止 KingExGEM
        /// </summary>
        /// <param name="msg"></param>
        public bool KingStop()
        {
            int rsp = m_kExGem.GEMStop();
            if (rsp >= 0)
            {
                AddMessage("[EQ ==> KingExGEM] Stop succeed");
                return true;
            }
            else
            {
                AddMessage("[EQ ==> KingExGEM] Stop failed. Return {0}", rsp);
                return false;
            }
        }

        /// <summary>
        /// 关闭 KingExGEM
        /// </summary>
        /// <param name="msg"></param>
        public bool KingClose()
        {
            int rsp = m_kExGem.GEMClose();
            if (rsp >= 0)
            {
                AddMessage("[EQ ==> KingExGEM] Close succeed");
                return true;
            }
            else
            {
                AddMessage(string.Format("[EQ ==> KingExGEM] Close failed. Return {0}", rsp));
                return false;
            }
        }

        #endregion

        #region 2. 连接状态

        /// <summary>
        /// 允许连接
        /// </summary>
        /// <param name="AAddMessage"></param>
        public void KingCommEnable()
        {
            int rsp = m_kExGem.GEMSetConnectionEnable(true);

            string content;
            if (rsp >= 0)
            {
                content = string.Format("[EQ ==> KingExGEM] Set Connection enable succeed");
                AddMessage(content);
            }
            else
            {
                content = string.Format("[EQ ==> KingExGEM] Set Connection enable failed. Return {0}", rsp);
                AddMessage(content);
            }
        }

        /// <summary>
        /// 禁止连接
        /// </summary>
        /// <param name="AAddMessage"></param>
        public void KingCommDisable()
        {
            int rsp = m_kExGem.GEMSetConnectionEnable(false);
            string content;
            if (rsp >= 0)
            {
                content = string.Format("[EQ ==> KingExGEM] Set Connection disable succeed");
                AddMessage(content);
            }
            else
            {
                content = string.Format("[EQ ==> KingExGEM] Set Connection disable failed. Return {0}", rsp);
                AddMessage(content);
            }
        }

        /// <summary>
        /// 获取连接状态
        /// </summary>
        /// <returns></returns>
        internal _eCommState GetCommState()
        {
            return eCommState;
        }

        #endregion

        #region 3.控制状态
        // 设备离线
        public void KingeqOfflineState()
        {
            int rsp = m_kExGem.GEMSetControlState(1);
            string content;
            if (rsp >= 0)
            {
                content = string.Format("[EQ ==> KingExGEM] Set Control State to EqOffline succeed");
                AddMessage(content);
            }
            else
            {
                content = string.Format("[EQ ==> KingExGEM] Set Control State to EqOffline failed. Return {0}", rsp);
                AddMessage(content);
            }
        }

        // 尝试在线
        public void KingattemptOnline()
        {
            int rsp = m_kExGem.GEMSetControlState(2);
            string content;
            if (rsp >= 0)
            {
                content = string.Format("[EQ ==> KingExGEM] Set Control State to AttemptOnline succeed");
                AddMessage(content);
            }
            else
            {
                content = string.Format("[EQ ==> KingExGEM] Set Control State to AttemptOnline failed. Return {0}", rsp);
                AddMessage(content);
            }
        }

        // 主机离线
        public void KinghostOfflineState()
        {
            int rsp = m_kExGem.GEMSetControlState(3);
            string content;
            if (rsp >= 0)
            {
                content = string.Format("[EQ ==> KingExGEM] Set Control State to HostOffline succeed");
                AddMessage(content);
            }
            else
            {
                content = string.Format("[EQ ==> KingExGEM] Set Control State to HostOffline failed. Return {0}", rsp);
                AddMessage(content);
            }
        }

        // 本地在线
        public void KingLocal()
        {
            int rsp = m_kExGem.GEMSetControlState(4);
            string content;
            if (rsp >= 0)
            {
                content = string.Format("[EQ ==> KingExGEM] Set Control State to Local succeed");
                AddMessage(content);
            }
            else
            {
                content = string.Format("[EQ ==> KingExGEM] Set Control State to Local failed. Return {0}", rsp);
                AddMessage(content);
            }
        }

        // 远程在线
        public void KingRemote()
        {
            int rsp = m_kExGem.GEMSetControlState(5);
            string content;
            if (rsp >= 0)
            {
                content = string.Format("[EQ ==> KingExGEM] Set Control State to Remote succeed");
                AddMessage(content);
            }
            else
            {
                content = string.Format("[EQ ==> KingExGEM] Set Control State to Remote failed. Return {0}", rsp);
                AddMessage(content);
            }
        }

        // 获取控制状态
        internal _eControlState GetControlState()
        {
            return eControlState;
        }

        #endregion

        #region 4.事件报告

        // 设置事件
        public bool KingSetEvent(int ceid)
        {
            int rsp = m_kExGem.GEMSetEvent(ceid);
            string content;
            if (rsp >= 0)
            {
                content = string.Format("[EQ ==> KingExGEM] Set Event succeed");
                AddMessage(content);
                return true;
            }
            else
            {
                content = string.Format("[EQ ==> KingExGEM] Set Event failed. Return {0}", rsp);
                AddMessage(content);
                return false;
            }
        }

        #endregion

        #region 5.变量

        // 设置变量值
        public bool KingSetVariable(Dictionary<int, string> variableList)
        {
            var list = variableList.Keys.Select(a => a).ToArray();
            var str = variableList.Values.Select(a => a).ToArray();
            int rsp = m_kExGem.GEMSetVariable(list, str);
            string content;
            if (rsp >= 0)
            {
                content = string.Format("[EQ ==> KingExGEM] Set Variable succeed");
                AddMessage(content);
                return true;
            }
            else
            {
                content = string.Format("[EQ ==> KingExGEM] Set Variable failed. Return {0}", rsp);
                AddMessage(content);
                return false;
            }
        }

        // 设置集合
        public bool KingSetVariableList(int vid, Semion semion)
        {
            int a = m_kExGem.GEMSetFmtVariable(vid, semion);
            return a == 0;
        }

        #endregion

        #region 6.常量

        // 设置ECV值，仅针对ECV变量进程变量值设置
        public void KingSetEcValue(Dictionary<int, string> ecvList)
        {
            var vids = ecvList.Keys.Select(a => a).ToArray();
            var strs = ecvList.Values.Select(a => a).ToArray();

            int rsp = m_kExGem.GEMSetEcvValue(vids, strs);

            string content;
            if (rsp >= 0)
            {
                content = string.Format("[EQ ==> KingExGEM] Set ECV succeed");
                AddMessage(content);
            }
            else
            {
                content = string.Format("[EQ ==> KingExGEM] Set ECV failed. Return {0}", rsp);
                AddMessage(content);
            }
        }

        #endregion

        #region 7.报警

        // 设置报警
        [Obsolete("不满足需求")]
        private void KingSetAlarm(int alarmId)
        {
            string content;
            int rsp = m_kExGem.GEMSetAlarm(alarmId, true);
            if (rsp >= 0)
            {
                content = string.Format("[EQ ==> KingExGEM] Set Alarm succeed");
                AddMessage(content);
            }
            else
            {
                content = string.Format("[EQ ==> KingExGEM] Set Alarm failed. Return {0}", rsp);
                AddMessage(content);
            }
        }

        // 清除报警
        [Obsolete("不满足需求")]
        private void KingClearAlarm(int alarmId)
        {
            string content;
            int rsp = m_kExGem.GEMSetAlarm(alarmId, false);
            if (rsp >= 0)
            {
                content = string.Format("[EQ ==> KingExGEM] Clear Alarm succeed");
                AddMessage(content);
            }
            else
            {
                content = string.Format("[EQ ==> KingExGEM] Clear Alarm failed. Return {0}", rsp);
                AddMessage(content);
            }
        }

        //获取所有启用的告警信息，，KingExGEM 将通过 OnGEMRspAllEnabledAlarm 返回信息
        public void KingGetAlarmInfo(int alarmID, out int aIcd, out string tx, out bool enable)
        {
            int rsp = m_kExGem.GEMGetAlarmInfo(new int[] { alarmID }, out int[] aIcds, out string[] Altxs, out bool[] enables);
            string content;
            if (rsp >= 0)
            {
                aIcd = aIcds[0];
                tx = Altxs[0];
                enable = enables[0];
                content = string.Format("[EQ ==> KingExGEM] Get All Alarm enable succeed");
                AddMessage(content);
            }
            else
            {
                aIcd = -1;
                tx = string.Empty;
                enable = false;
                content = string.Format("[EQ ==> KingExGEM] Get All Alarm enable failed. Return {0}", rsp);
                AddMessage(content);
            }
        }

        #endregion

        /// <summary>
        /// 获取当前RFID状态
        /// </summary>
        /// <param name="lotID"></param>
        /// <returns>
        /// 0:等待MES回复
        /// 1:OK
        /// 2:NG
        /// </returns>
        public int GetRfidStatus(string carrierID)
        {
            if (rfidReadStatus.TryRemove(carrierID, out bool val))
            {
                return val ? 1 : 2;
            }

            return 0;
        }

        private void AddMessage(string format, params object[] args)
        {
            if (AddMessageEvent != null)
            {
                AddMessageEvent(format, args);
            }
        }
        private void AddMessage2(string format)
        {
            if (AddMessage2Event != null)
            {
                AddMessage2Event(format);
            }
        }
    }
}
